import { mapper } from '../widget/constants'
export function useWidgetTools() {
  const renderErrorBar = (params, api) => {
    const xValue = api.value(0)
    const low = api.value(1)
    const hight = api.value(2)
    const lowPoint = api.coord([xValue, low])
    const highPoint = api.coord([xValue, hight])
    const halfWidth = api.size([1, 0])[0] * 0.1
    const style = {
      stroke: api.visual('color'),
      fill: undefined
    }
    return {
      type: 'group',
      children: [
        {
          type: 'line',
          transition: ['shape'],
          shape: {
            x1: highPoint[0] - halfWidth,
            y1: highPoint[1],
            x2: highPoint[0] + halfWidth,
            y2: highPoint[1]
          },
          style: style
        },
        {
          type: 'line',
          transition: ['shape'],
          shape: {
            x1: highPoint[0],
            y1: highPoint[1],
            x2: lowPoint[0],
            y2: lowPoint[1]
          },
          style: style
        },
        {
          type: 'line',
          transition: ['shape'],
          shape: {
            x1: lowPoint[0] - halfWidth,
            y1: lowPoint[1],
            x2: lowPoint[0] + halfWidth,
            y2: lowPoint[1]
          },
          style: style
        }
      ]
    }
  }

  const renderHistogram = (params, api) => {
    const min = api.value(0)
    const max = api.value(1)
    const count = api.value(2)
    const start = api.coord([0, max])
    const size = api.size([count, max - min])
    const style = api.style()
    return {
      type: 'rect',
      shape: {
        x: start[0],
        y: start[1],
        width: size[0],
        height: size[1]
      },
      style: style
    }
  }

  const formatNumber = (val: number, digits = 2) => {
    return val.toFixed(digits)
  }

  const transKeyToName = (key: string) => {
    return mapper[key] || ''
  }

  const getRandomHex = () => {
    return Math.floor(Math.random() * 256)
      .toString(16)
      .padStart(2, '0')
  }

  const getColorMap = (keys) => {
    return keys?.reduce((acc, key) => {
      acc[key] = `#${getRandomHex()}${getRandomHex()}${getRandomHex()}`
      return acc
    }, {})
  }

  return {
    renderErrorBar,
    renderHistogram,
    formatNumber,
    transKeyToName,
    getColorMap
  }
}
